package com.example.controller.config.security.filter;

import com.example.common.JwtUtils;
import com.example.common.RedisUtils;
import com.example.controller.config.security.exception.CustomerAuthenticationExceotion;
import com.example.controller.config.security.handler.LoginFailureHandler;
import com.example.controller.config.security.service.CustomerUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 验证token过滤器
 */
@Component
public class CheckTokenFilter extends OncePerRequestFilter {

    public static final String LOGIN_URL = "/api/umsAdmin/login";

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private CustomerUserDetailsService customerUserDetailsService;

    @Autowired
    private LoginFailureHandler loginFailureHandler;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        try {
            //获取当前请求url地址
            String requestURI = request.getRequestURI();
            String username = request.getParameter("username");
            if (!requestURI.equals(LOGIN_URL)) {
                //进行token验证
                this.validateToken(request);
            }
        }catch (AuthenticationException e){
            loginFailureHandler.onAuthenticationFailure(request,response,e);
        }
        //登录请求不需要携带token
        doFilter(request,response,filterChain);
    }

    /**
     * 验证token信息
     */
    private void validateToken(HttpServletRequest request) {
        //获取前端提交的token信息
        //从headers头部获取token信息
        String token = request.getHeader("token");
        //如果请求头部中没有携带token，则从请求的参数中获取token
        if(ObjectUtils.isEmpty(token)){
            //从参数中获取
            token = request.getParameter("token");
        }
        //如果参数中没有token信息
        if(ObjectUtils.isEmpty(token)){
            throw new CustomerAuthenticationExceotion("token不存在");
        }
        //判断redis中是否存在token信息

        String tokenkey = "token_" + token;
        String redisToken = null == redisUtils.get(tokenkey) ? null : redisUtils.get(tokenkey) .toString() ;
        //判断Redis中是否存在token信息 如果为空 则表示token失效
        if(ObjectUtils.isEmpty(redisToken)){
            throw new CustomerAuthenticationExceotion("token已过期");
        }
        //如果token和Redis中的token不一致 验证失败
        if(!token.equals(redisToken)){
            throw new CustomerAuthenticationExceotion("token验证失败");
        }
        //如果token是存在的 则从token中解析出用户名
        String username = jwtUtils.getUsernameFromToken(token);
        //判断用户名是否为空
        if(ObjectUtils.isEmpty(username)){
            throw new CustomerAuthenticationExceotion("token解析失败！");
        }
        //获取用户信息
        UserDetails userDetails = customerUserDetailsService.loadUserByUsername(username);
        //判断用户信息是否为空
        if(null == userDetails){
            throw new CustomerAuthenticationExceotion("token验证失败");
        }
        //创建用户身份认证对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        //设置请求信息
        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        //将验证信息交给spring Security上下文
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);


    }
}
